import numpy as np
from numpy import *
import os
import matplotlib
import matplotlib.pyplot as plt
import operator
def createDataSet():
    group = np.array([[1.0,1.1],[1.0,1.0], [0,0], [0,0.1]])
    labels = ['A', 'A', 'B', 'B']
    return group, labels
#k-近邻算法
def classify0(inX, dataSet, labels, k):
    dataSetSize = dataSet.shape[0]
    diffMat = tile(inX, (dataSetSize, 1)) - dataSet
    #print('--', diffMat, '--')
    sqDiffMat = diffMat ** 2
    #print('sqDiffMat', sqDiffMat)
    sqDistances = sqDiffMat.sum(axis=1)
    #print('sqDistances', sqDistances)
    distances = sqDistances ** 0.5
    print(distances)
    sortedDistIndicies = distances.argsort()
    print(sortedDistIndicies)
    classCount = {}
    for i in range(k):
        voteIlabel = labels[sortedDistIndicies[i]]
        #print(voteIlabel)
        classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1
        print(classCount[voteIlabel])
    print(classCount.items())
    sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)

    #b = operator.itemgetter(1)
    #print(b(classCount.items()))
    print(sortedClassCount)
    return sortedClassCount[0][0]
def file2matrix(filename):
    file = open(filename)
    arrayLines = file.readlines()
    numofLines = len(arrayLines)
    returnMat = zeros((numofLines, 3))
    classLabelVector = []
    index = 0
    for line in arrayLines:
        line = line.strip()
        listFromLine = line.split('\t')
        returnMat[index,:] = listFromLine[0:3]
        classLabelVector.append(int(listFromLine[-1]))
        index += 1
    return returnMat, classLabelVector
def createMatplotlib(returnMat, classLabelVector):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    #ax.scatter(returnMat[:,1], returnMat[:,2])
    ax.scatter(returnMat[:,1], returnMat[:,2],15.0*array(classLabelVector), 15.0*array(classLabelVector))
    plt.show()
def autoNorm(dataSet):
    minVals = dataSet.min(0)
    print(minVals)
    maxVals = dataSet.max(0)
    print(maxVals)
    ranges = maxVals - minVals
    normDataSet = zeros(shape(dataSet))
    m = dataSet.shape[0]
    normDataSet = dataSet - tile(minVals, (m, 1))
    normDataSet = normDataSet / tile(ranges, (m, 1))
    return normDataSet, ranges, minVals
def datingClassTest():
    hoRatio = 0.10
    datingDataMat, datingLabels = file2matrix("datingTestSet2.txt")
    normMat, ranges, minVals = autoNorm(datingDataMat)
    m = normMat.shape[0]
    numTestVecs = int(m * hoRatio)
    errorCount = 0.0
    for i in range(numTestVecs):
        #[i,:]表示第i条元素
        classfilterResult = classify0(normMat[i,:], normMat[numTestVecs:m, :],\
                            datingLabels[numTestVecs:m], 3)
        print('The classfilter came back with: %d, the real answer is: %d'\
              % (classfilterResult, datingLabels[i]))
        if(classfilterResult != datingLabels[i]):
            errorCount += 1.0
    print('the total error rate is: %f' % (errorCount / float(numTestVecs)))
def classifyPerson():
    resultMap = ['not at all', 'in small does', 'in large does']
    file = open('data.txt')
    arrayLines = file.readlines()
    numOfLines = len(arrayLines)
    for line in arrayLines:
        line = line.strip()
        lineFromList = line.split(' ')
        percentTats = float(lineFromList[1])
        ffMiles = float(lineFromList[0])
        iceCream = float(lineFromList[2])
        datingDataMat, datingLabels = file2matrix('datingTestSet2.txt')
        normMat, ranges, minVals = autoNorm(datingDataMat)
        inArr = array([ffMiles, percentTats, iceCream])
        print("inArr ", inArr)
        inX = (inArr-minVals) / ranges
        classifierResult = classify0(inX, normMat, datingLabels, 3)
        print("You will probably like this person: ", \
            resultMap[classifierResult - 1])
group, labels = createDataSet()
input = array([1.1, 0.3])
K = 4
output = classify0(input, group, labels, K)
print("Test data: ", input, "Out data:", output)
#print(zeros((6,3)))
'''line = '38768	5.308409	0.030683	largeDoses'
listFromLine = line.split('\t')
returnMat = zeros((1,3))
returnMat[0,:] = listFromLine[0:3]
labelVector = []
print(returnMat)
print(listFromLine[0:3])
labelVector.append(listFromLine[-1])
print(labelVector)
'''
returnMat, classLabelVector = file2matrix('datingTestSet2.txt')
#print(classLabelVector)
#createMatplotlib(returnMat, classLabelVector)
#datingClassTest()
"""
    矩阵归一化数据 newValue = (value - min) / (max - min)
"""
'''norm = tile(2, (3, 1))
data = array([[4,3], [7,4], [2,5]])
norm = norm - data
print (norm)
norm = norm / tile(2, (3,1))
print(norm)'''
normMat, ranges, minVals = autoNorm(returnMat)
#print(normMat[2,:], normMat[])
#print(classify0(norm))
#print(autoNorm(returnMat))
#矩阵的min()和max() 表示的向量所有组合间的最大最小值
#data = array([[4,3], [7,4], [2,5]])
#print(data.max(0))
#print(data[1,:])
#print(data[1])
#classifyPerson()
arr = array([1,4,3,-1,6,9])


